/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jsalon.repo;

import jamjun.infra.common.DBHelper;
import jamjun.infra.common.DataType;
import jamjun.infra.common.SqlParameter;
import jamjun.infra.lang.JJDate;
import jamjun.infra.lang.JJString;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsalon.enumtype.Doctype;
import jsalon.enumtype.Gender;
import jsalon.model.Customer;
import jsalon.model.SysNumber;
import jsalon.repo.irepo.ISysNumberRepo;

/**
 *
 * @author Java
 */
public  class SysNumberRepo implements ISysNumberRepo {

    @Override
    public PreparedStatement updateRunning(String domainID, Doctype doctype,Connection conn) throws Exception {
        //<editor-fold desc="validate parameter">
            if(JJString.IsNullOrEmty(domainID)){
                throw new Exception("not have domainID.");
            }
            if(doctype == null){
                throw new Exception("not have docID.");
            }
        //</editor-fold>
        PreparedStatement pstmt = null;
        try { 
            //<editor-fold desc="model filter.">
            List<SqlParameter> SqlParameterList = new ArrayList<>();
            SqlParameter sqlParameter1 = new  SqlParameter();
            sqlParameter1.SetString("@domainID",domainID);
            SqlParameterList.add(sqlParameter1);
            SqlParameter sqlParameter2 = new  SqlParameter();
            sqlParameter2.SetString("@docID",doctype.strValue());
            SqlParameterList.add(sqlParameter2);
            String sqlFilterCMD = " where domainID=@domainID and docID=@docID ";
            //</editor-fold>
            String sql = "update sys_number set running= running+1 " + sqlFilterCMD;
            pstmt = DBHelper.setPreparedStatement(conn,sql,SqlParameterList);
            return pstmt;
        } catch (Exception ex) {
            Logger.getLogger(SysNumberRepo.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception(ex.getMessage());
        } finally {
        } 
    }
    
    public SysNumber update(SysNumber data) throws Exception {
        //<editor-fold desc="validate model">
        if(JJString.IsNullOrEmty(data.domainID)){
            throw new Exception("not have domainID.");
        }
        if(JJString.IsNullOrEmty(data.docID)){
            throw new Exception("not have docID.");
        }
        //</editor-fold>
        //<editor-fold desc="intial valiable">
        //</editor-fold>
        Connection conn = null;    
        //Statement stmt = null;
        PreparedStatement pstmt = null;
        try { 
            List<SqlParameter> SqlParamList;
            SqlParamList = new ArrayList<>();
            conn = DBHelper.getConnection(jamjun.infra.model.DBConnectionName.jsalon.Name());
            String sql = "update sys_number set running=@running,year=@year,month=@month"
                    +" where domainID=@domainID and docID=@docID";
            SqlParamList.add(new SqlParameter("@domainID",data.domainID, DataType.typeString));
            SqlParamList.add(new SqlParameter("@docID",data.docID, DataType.typeString));
            SqlParamList.add(new SqlParameter("@running",data.running, DataType.typeInt));
            SqlParamList.add(new SqlParameter("@year",data.year, DataType.typeInt));
            SqlParamList.add(new SqlParameter("@month",data.month, DataType.typeInt));
            
            pstmt = DBHelper.setPreparedStatement(conn,sql,SqlParamList);
            pstmt.executeUpdate(); // execute insert statement
            conn.close();
            return data;
        } catch (SQLException ex) {
            Logger.getLogger(CustomerRepo.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception(ex.getMessage());
        } finally {
            if(pstmt != null) {pstmt.close();}
            if(conn != null) {conn.close();} 
        } 
    }

    @Override
    public SysNumber getData(String domainID, Doctype doctype) throws Exception {
        //<editor-fold desc="validate parameter">
            if(JJString.IsNullOrEmty(domainID)){
                throw new Exception("not have domainID.");
            }
            if(doctype == null){
                throw new Exception("not have docID.");
            }
        //</editor-fold>
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try { 
            conn = DBHelper.getConnection(jamjun.infra.model.DBConnectionName.jsalon.Name());
            //<editor-fold desc="model filter.">
            List<SqlParameter> SqlParameterList = new ArrayList<>();
            SqlParameter sqlParameter1 = new  SqlParameter();
            sqlParameter1.SetString("@domainID",domainID);
            SqlParameterList.add(sqlParameter1);
            SqlParameter sqlParameter2 = new  SqlParameter();
            sqlParameter2.SetString("@docID",doctype.strValue());
            SqlParameterList.add(sqlParameter2);
            String sqlFilterCMD = " where domainID=@domainID and docID=@docID ";
            //</editor-fold>
            //<editor-fold desc="paging data.">
            String sql = "select * from sys_number "+ sqlFilterCMD;
            pstmt = DBHelper.setPreparedStatement(conn,sql,SqlParameterList);
            rs = pstmt.executeQuery();
            SysNumber model = null;
            rs.last();
            int size = rs.getRow();
            rs.beforeFirst();
            if(size > 0){
                model = new SysNumber();
                while(rs.next()){
                   model.domainID = rs.getString("domainID");
                   model.docID = rs.getString("docID");
                   model.running = rs.getInt("running");
                   model.year = rs.getInt("year");
                   model.month = rs.getInt("month");
                }
            }
            rs.close();
            return model;
        } catch (SQLException ex) {
            Logger.getLogger(SysNumberRepo.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception(ex.getMessage());
        } finally {
            if(rs != null){rs.close(); }
            if(conn != null){conn.close();}
        } 
    }
    
    public SysNumber checkAndUpdateDate(String domainID, Doctype doctype) throws Exception{
        try{
            SysNumber sysNumber = null;
            sysNumber =this.getData(domainID, doctype);
            Date dateNow = new Date();
            int current_month = Integer.parseInt(JJDate.GetMonth(dateNow));
            int current_year = Integer.parseInt(JJDate.GetYear(dateNow));
            if(sysNumber == null){
                //insert new
            }else{
                boolean isUpdateDate = false;
                //check date
                if(sysNumber.year < current_year){
                    isUpdateDate = true;
                }else{
                    //ถ้าเป็นปีเดียวกับ แต่เดือนน้อยกว่า
                    if(sysNumber.month < current_month){
                        isUpdateDate = true;
                    }
                }
                if(isUpdateDate == true){
                    sysNumber.month = current_month;
                    sysNumber.year = current_year;
                    sysNumber.running = 0;
                    sysNumber = this.update(sysNumber);
                }
            }
            return sysNumber;
        }catch(Exception ex){
            throw ex;
        }
    }
    
    public String getCode(String domainID, Doctype doctype) throws Exception{
        try { 
            String code = "";
            //get number
            SysNumber sysNumber = null;
            sysNumber = this.checkAndUpdateDate(domainID,doctype);
            if(sysNumber == null){
                throw new Exception("sysNumber is null");
            }
            Date dateNow = new Date();
            String year = JJDate.GetYear(dateNow);
            String month = JJDate.GetMonth(dateNow);
            int running = sysNumber.running + 1;
            String strRunning = String.format("%03d",running);
            if(doctype == Doctype.customer){
                code = year + "" + month + "" + strRunning;
            }
            return code;
        }catch(Exception ex){
            throw ex;
        }
    }
    
}
